from flask import Blueprint
from flask import render_template
from flask import request,json,jsonify
import requests
from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)  # 允许跨域请求

CORS(app, resources={r"/chat/*": {"origins": "*"}}, supports_credentials=True, methods=['GET', 'POST', 'OPTIONS'], allow_headers=["Content-Type"])

main = Blueprint('main', __name__, url_prefix='/chat')

@main.route('/', methods=['post','get'])
def chat():
   data = request.get_json()

   if not data or 'message' not in data:
      return jsonify({"error": "No message found"}), 400

   # 提取 message 参数
   message = data.get('message')

   print(f"Received message: {message}")

   # 返回 JSON 响应
   response = {
      "message": f"Your message was: {message}"
   }

   return jsonify(response), 200  # 返回 JSON 响应和状态码 200



   #
   # print(request.get_data())
   # data = request.get_json()
   # print(data)
   # if data:
   #    message = data.get("message")
   #    print(message)
   #    return "Received", 200
   # else:
   #    return "No JSON Data", 400

   return "Use POST to send data"
   # print(request.get_data())
   # message = request.values.get("name")
   # print(message)
   # return_dict['result'] = "%s" % (message)
   # # print(return_dict)
   # return json.dumps(return_dict, ensure_ascii=False)


def langflow(input_text):
   url = "http://192.168.31.122:7960/api/v1/run/ragtest02"
   headers = {"Content-Type": "application/json"}

   data = {
      "input_value": input_text,
      "output_type": "chat",
      "input_type": "chat",
      "tweaks": {
         "Prompt-tVM2Q": {
            "template": "已知信息:\n{context}\n\n用户问：\n{query}",
            "context": "",
            "query": ""
         },
         "ChatInput-z20Ux": {
            "files": "",
            # "input_value": "霍因有几台服务器",
            "sender": "User",
            "sender_name": "User",
            "session_id": "",
            "should_store_message": True
         },
         "Chroma-HVzdt": {
            "allow_duplicates": False,
            "chroma_server_cors_allow_origins": "",
            "chroma_server_grpc_port": None,
            "chroma_server_host": "",
            "chroma_server_http_port": None,
            "chroma_server_ssl_enabled": False,
            "collection_name": "sun02",
            "limit": None,
            "number_of_results": 10,
            "persist_directory": "sun02",
            "search_query": "",
            "search_type": "Similarity"
         },
         "OllamaEmbeddings-qR3Z2": {
            "base_url": "http://localhost:11434",
            "model": "smartcreation/bge-large-zh-v1.5:f16",
            "temperature": 0.1
         },
         "ParseData-OCisO": {
            "sep": "\n",
            "template": "{text}"
         },
         # "TextOutput-j5JSy": {
         #     "input_value": ""
         # },
         "ChatTongyi-qkTiC": {
            # "input_value": "",
            "model": "qwen-turbo",
            "stream": False,
            "system_message": "",
            "temperature": 0.95,
            "tongyi_sk": "sk-031954fbed5c4d2f86e486a6cac7162f",
            "top_p": 0.8
         }
      }
   }

   # 5、发送post请求进行测试
   response = requests.post(url, headers=headers, data=json.dumps(data))
   # 检查响应状态码
   if response.status_code == 200:
      try:
         # logger.info(f"输出响应内容是: {response.status_code}\n")
         # logger.info(f": {response.json()}\n")
         # 解析具体回复的内容
         # content = response.json()['outputs'][0]['outputs'][0]['results']['message']['data']['text']  #本地大模型格式
         content = response.json()['outputs'][0]['outputs'][0]['results']['text']['data']['text']  # 通义访问API的格式

         print(f"输出响应内容是: {content}\n")
      except requests.exceptions.JSONDecodeError:
         # 响应不是JSON格式
         print("Response content is not valid JSON")
   else:
      print(f"Request failed with status code {response.status_code}")

